package com.xq.spring.jdbctemplate;

import com.xq.hibernate.sboot.entity.Customer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能说明:class implements Spring Boot’s CommandLineRunner, which means it will execute the run() method after <b>the application context</b> is loaded up.
 * <p>创建时间: 2018-11-02 20:26</p>
 *
 * @author 郭凯强
 * @version 1.0-SNAPSHOT
 */
@SpringBootApplication
public class Application implements CommandLineRunner {
    private final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Spring Boot automatically creates a JdbcTemplate. The @Autowired JdbcTemplate field automatically loads it and makes it available.
     */
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        //install some DDL using JdbcTemplate’s `execute` method
        logger.info("Creating tables");
        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute("CREATE TABLE customers(" +
                "id SERIAL,first_name VARCHAR(255),last_name VARCHAR(255))");

        //Split up the array of whole names into an array of first/last name
        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream().map(name -> name.split(" "))
                .collect(Collectors.toList());
        // Use a Java 8 stream to print out each tuple of the list
        splitUpNames.forEach(name -> logger.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

        // Uses JdbcTemplate's batchUpdate operation to bulk load data
        // For single insert statements, JdbcTemplate’s `insert` method is good. But for multiple inserts, it’s better to use `batchUpdate`.
        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name,last_name) VALUES(?,?)", splitUpNames);

        logger.info("Querying for customer records where first_name='Josh':");
        jdbcTemplate.query("SELECT id,first_name,last_name FROM customers WHERE first_name=?", new Object[]{"Josh"},
                (result, rowNum) -> new Customer(result.getLong("id"), result.getString("first_name"), result.getString("last_name")))
                .forEach(customer -> logger.info(customer.toString()));
    }
}


